<template>
  <!-- 添加和修改课时表单 -->
  <el-dialog :visible.sync="dialogVisible" :title="title" @close="close">
    <el-form
      ref="periodForm"
      :rules="periodRules"
      status-icon
      :model="period"
      label-width="120px">

      <el-form-item label="课时标题" prop="periodName">
        <el-input v-model="period.periodName" maxlength="50" show-word-limit/>
      </el-form-item>

      <el-form-item label="课时排序">
        <el-input-number v-model="period.sort" :min="0" :max="999"/>
      </el-form-item>

      <el-form-item label="是否免费">
        <el-radio-group v-model="period.free">
          <el-radio-button :label="0" v-if="isFree !== true">收费</el-radio-button>
          <el-radio-button :label="1">免费</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="上传文档">
        <el-upload
          :on-success="handleFileUploadSuccess"
          :on-exceed="handleUploadExceed"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          :before-remove="beforeVodRemove"
          :file-list="fileList"
          accept=".zip,.rar"
          :action="BASE_API+'/oss/teacher/file/upload?host=course&courseId='+period.courseId"
          :limit="1"
          class="upload-demo">
          <el-button size="medium" type="primary">上传文档</el-button>
          <div slot="tip" class="el-upload__tip">文件大小最大支持20MB，<br>
            支持ZIP、RAR等压缩文件格式上传，<br>
            上传期间请不要关闭本页面！
          </div>
        </el-upload>

        <div>
          <span>{{ statusText }}</span>
        </div>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { savePeriod,getPeriodById,updatePeriodById } from '@/api/period'
  import { validNormal } from '@/utils/validate'
  import { deleteOssFileByUrl } from '@/api/oss'


  export default {

    // 父组件向子组件传值
    props: {
      courseId: {
        type: String,
        default: null
      },
      isFree: {
        type: Boolean,
        default: false
      }
    },
    data() {

      //检验课时名称
      const validateName = (rule, value, callback) => {
        if (value.length < 5 || value > 50 || !validNormal(value)){
          callback(new Error("请输入正确的章节名称，长度要求为5-50，且不能输入特殊字符"))
        }
        else callback()
      }

      return {
        title: '',
        periodCategory: 0,
        dialogVisible: false,
        period: {
          periodId: '',
          courseId: '',
          chapterId: '',
          periodName: '',
          videoName: '',
          sort: 0,
          free: 0,
        },

        //检验规则
        periodRules:{
          periodName: [{trigger: 'blur',validator: validateName}]
        },

        statusText: '',
        fileList: [], // 上传文档列表
        BASE_API: process.env.VUE_APP_BASE_API, // 接口API地址
        OSS_URL: 'http://czz-education.oss-cn-shenzhen.aliyuncs.com/', //阿里云oss地址

      }
    },

    methods: {
      open(chapterId, periodId) {
        this.dialogVisible = true
        this.period.chapterId = chapterId
        this.period.courseId = this.courseId
        this.period.doc = 1

        if (this.isFree) {
          this.period.free = 1
        }

        if (periodId) {
          this.title = '修改课程文档课时'
          getPeriodById(periodId).then(result => {
            this.period = result.data.item

            delete this.period.gmtCreate
            delete this.period.gmtModified

            if (this.period.docUrl && this.period.docName) {
              this.fileList = [{ 'name': this.period.docName }]
            }

          })
        }
        else {
          this.title = '新增课程文档课时'
        }
      },

      close() {
        this.$refs.periodForm.resetFields();
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },

      resetForm() {
        this.period.periodName = ''
        this.period.sort = 0
        this.period.chapterId = ''
        this.period.periodId = ''
        this.period.courseId = ''
        this.period.free = 0
        this.period.videoId = ''
        this.period.videoName = ''
        this.statusText = ''
        this.fileList = []
      },

      saveOrUpdate() {
        this.$refs.periodForm.validate((valid) => {
          if (valid) {
            //检验通过
            //判断是否有上传文件或者视频
            if (!this.period.docUrl) {
              this.$message.error("请上传课程文档！")
              return false
            }
            if (!this.period.periodId) {
              this.save()
            } else {
              this.update()
            }
          } else {
            return false
          }
        })
      },

      save() {
        this.period.courseId = this.courseId
        savePeriod(this.$qs.stringify(this.period)).then(result => {
          if (result.code === 20000) {
            this.$message({
              type: 'success',
              message: '保存成功！'
            })
            // 关闭组件
            this.close()
            // 调用父组件监听函数
            this.$emit('onSaveSuccess')
          }
        })
      },

      update() {
        updatePeriodById(this.period.periodId, this.$qs.stringify(this.period)).then(result => {
          if (result.code === 20000) {
            this.$message({
              type: 'success',
              message: '修改成功！'
            })
            // 关闭组件
            this.close()
            // 调用父组件监听函数
            this.$emit('onSaveSuccess')
          }
        })
      },

      // 文档/视频删除前回调
      beforeVodRemove(file) {
        if (file && file.status==="success") {
          return this.$confirm(`确定移除 ${file.name}？`)
        }
      },

      // 上传多个文档/视频
      handleUploadExceed() {
        this.$message.warning('想要重新上传文件，请先删除已上传的文件')
      },

      // 文档成功上传回调
      handleFileUploadSuccess(result){
        this.period.docName = result.data.item.fileName
        this.period.docUrl = result.data.item.url
        this.statusText = '文件上传完毕！'
      },


      // 文档确定删除回调
      handleFileRemove(file, fileList){
        if (file && file.status==="success") {
          const url = this.period.docUrl.replace(this.OSS_URL,'').replace(/\//g, '&&')
          deleteOssFileByUrl(url).then(result=>{
            if (result.code === 20000){
              this.period.docName = ''
              this.period.docUrl = ''

              if (this.period.periodId){
                // 更新课时信息
                updatePeriodById(this.period.periodId, this.$qs.stringify(this.period)).then(result => {})
                this.$message({
                  type: 'success',
                  message: result.message
                })
                // 获取最新乐观锁
                getPeriodById(this.period.periodId).then(result => {
                  this.period = result.data.item

                  delete this.period.gmtCreate
                  delete this.period.gmtModified
                })
              }

            }
          })
        }
      },

      // 文档上传前检查
      beforeUpload(file){
        //获取后缀
        const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)

        const isRAR = suffix === 'rar';
        const isZIP = suffix === 'zip';
        const isDOC = (isRAR || isZIP)
        const isLt20M = file.size / 1024 / 1024 < 20;

        if (!isDOC) {
          this.$message.error('上传文档只能是 RAR 或 ZIP 格式！');
          return isDOC
        }

        if (!isLt20M) {
          this.$message.error('上传文档大小不能超过 20MB！');
          return isLt20M
        }
      }

    }
  }
</script>

<style scoped>

</style>
